<template>
  <div class="login">
    <!-- 手机号码密码登录 -->
    <div class="loginByPhone" v-if="this.loginmode == '1'">
      <el-form
        :model="userinfo"
        ref="ruleForm"
        label-position="right"
        class="loginForm"
        :rules="loginRules"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="userinfo.phone"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="userinfo.password"
            placeholder="请输入密码"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="loginButton" @click="LoginByPhone">登录</div>

      <div class="othersLogin">
        <div class="registerButton">
          没有账户 去<span @click="goToRegister">注册</span>
        </div>
        <div class="scan" @click="goToScan">扫码登录</div>
      </div>
    </div>
    <!-- 扫码登录 -->
    <div class="loginByScan" v-else-if="this.loginmode == '2'">
      <div class="top">
        <img src="../../assets/scan.png" alt="" />
        <div class="scan-right">
          <div class="title">扫码登录</div>
          <div class="scanImg">
            <img :src="qrImg" alt="" />
          </div>
          <span v-if="this.loginStatus == 1">使用网易云音乐App扫码登录</span>
          <span v-else-if="this.loginStatus == 2">请在手机上确认登录</span>
        </div>
      </div>
      <div class="bottom" @click="goToPhone">其他模式登录</div>
    </div>
    <!-- 注册 -->
    <div class="register" v-if="this.loginmode == '0'">
      <register></register>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import Register from "../register/Register.vue";
let timer;
let timestamp = Date.parse(new Date());

export default {
  components: { Register },
  name: "Login",
  data() {
    // 自定义手机号码验证规则
    const validPhone = (rule, value, callback) => {
      const phoneRge =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!value) {
        return callback(new Error("请输入电话号码"));
      }
      if (!phoneRge.test(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    };
    // 自定义密码校验规则
    const validPwd = (rule, value, callback) => {
      const length = value && value.length;
      const pwdReg = /^[a-zA-Z0-9_]+$/;
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (length < 4) {
        callback(new Error("密码必须大于4位"));
      } else if (length > 12) {
        callback(new Error("密码必须小于12位"));
      } else if (!pwdReg.test(value)) {
        callback(new Error("密码必须是英文数字或下划线组成!"));
      } else {
        callback();
      }
    };
    return {
      // 用户信息
      userinfo: {
        phone: "",
        password: "",
      },
      // 登录校验
      loginRules: {
        phone: [{ validator: validPhone, trigger: "blur" }],
        password: [{ validator: validPwd, trigger: "blur" }],
      },
      // 二维码图片
      qrImg: "",
      key: "",
      // 扫码时登录状态
      loginStatus: 1, //1代表等待扫码 2代表等待确认 3代表登录成功
    };
  },
  props: {
    handleCloseLogin: {
      type: Function,
      default: () => {},
    },
  },
  computed: {
    ...mapState(["loginmode"]),
  },
  mounted() {
    this.loginValidate();
    // 将表单元素传给父组件
    console.log(this.$refs.ruleForm);
    this.$emit("resetLoginForm", this.$refs.ruleForm);
  },
  methods: {
    ...mapMutations(["updateLoginmode"]),
    // 手机登录
    async LoginByPhone() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return this.$message.error("您输入的信息有误");
        const { data: res } = await this.$http("/login/cellphone", {
          params: {
            ...this.userinfo,
          },
        });
        if (res.code == 200) {
          // 表示登录成功
          // 将userInfo传回父组件
          this.$emit("getUserInfo", res.profile);
          // 将用户数据保存在localStroage中
          localStorage.setItem("userInfo", JSON.stringify(res.profile));
          this.$message.success("登录成功!");
          // 修改vuex中的登录状态
          this.$store.commit("updataLoginState", true);
          this.userinfo.phone = "";
          this.userinfo.password = "";
        }
      });
    },
    // 跳转到扫码界面
    goToScan() {
      this.updateLoginmode("2");
      this.loginByScan();
    },
    goToPhone() {
      this.updateLoginmode("1");
    },
    // 获取登录状态
    async getLoginStatus() {
      const { data: status } = await this.$http("/login/status");
      console.log(status);
      localStorage.setItem("userInfo", JSON.stringify(status.data.profile));
    },
    //  扫码登录
    async loginByScan() {
      // 生成一个key
      const { data: res } = await this.$http("/login/qr/key");
      this.key = res.data.unikey;
      // 生成二维码
      const result = await this.$http("/login/qr/create", {
        params: {
          key: res.data.unikey,
          timestamp,
          qrimg: true,
        },
      });
      this.qrImg = result.data.data.qrimg;
    },
    // 验证扫码
    loginValidate() {
      timer = setInterval(async () => {
        // 检测扫码状态
        const { data: resCode } = await this.$http("/login/qr/check", {
          params: {
            key: this.key,
            timestamp,
          },
        });
        if (resCode.code === 800) {
          clearInterval(timer);
          this.$message.error("二维码已过期，请稍后再试");
        }
        if (resCode.code === 802) {
          this.loginStatus === 2;
        }
        if (resCode.code === 803) {
          clearInterval(timer);
          this.$message.success("登陆成功");
          console.log(resCode);
          this.$emit("showloginDialogVisible");
          this.$store.commit("updataLoginState", true);
          this.getLoginStatus();
          // 刷新页面
          setTimeout(() => {
            this.$router.go(0);
          }, 1000);
        }
      }, 3000);
    },
    // 跳转到注册界面
    goToRegister() {
      this.updateLoginmode("0");
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  padding: 20px;
}
.loginButton {
  width: 80%;
  height: 40px;
  text-align: center;
  line-height: 40px;
  background-color: #ec4141;
  margin: 10px auto;
  color: #fff;
  cursor: pointer;
}

.othersLogin {
  display: flex;
  justify-content: space-around;
  align-items: center;
  .registerButton span {
    color: #ec4141;

    cursor: pointer;
  }
  .registerButton span:hover {
    text-decoration: underline;
  }
  .scan {
    cursor: pointer;
  }
  .scan:hover {
    text-decoration: underline;
  }
}
.top {
  display: flex;
  justify-content: space-around;
  align-items: center;
  img {
    width: 125px;
    height: 220px;
  }
  .scan-right {
    height: 250px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: column;
    .title {
      font-size: 18px;
      // height: 30px;
    }
    .scanImg {
      img {
        width: 140px;
        height: 140px;
      }
    }
    span {
      line-height: 30px;
      margin-top: -34spx;
    }
  }
}
.bottom {
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  margin-top: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  color: #666666;
  font-size: 12px;
  cursor: pointer;
}
</style>
